<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column width="200" prop="name" label="角色" align="center">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" prop="state" label="启用" align="center">
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1?"已起用":row.state===0?"未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="assignPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="确定删除吗？" @onConfirm="confirmDelete(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="height:60px" align="middle">
        <el-pagination
          background
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev,pager,next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog v-dialogDrag width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="formData" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model=" formData.state" size="mini" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :row="3" size="mini" style="width:300px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 展示分配权限弹框 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置菜单树 -->
      <!-- check-strictly 父子组件是否级联勾选   -->
      <!-- default-checked-keys 默认选择的接口id集合 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="assignOk">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, assignPerm, delRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Approvals',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1,
        pagesize: 15,
        total: 0
      },
      showDialog: false,
      formData: {
        name: '',
        description: '',
        state: 0 // 默认未启用  0 管理 1 打开
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false, // 展示权限弹框
      permissionData: [], // 接受权限数据
      currentUserId: '', // 点击分配权限时候记录下是给谁分配权限
      permIds: [] // 该用户已经拥有的角色 id 集合
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取数据列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      // 针对每一行数据添加一个编辑标记
      this.list.forEach(item => {
        // item.isEdit = false // 这样添加的属性不具有响应式特点
        // 动态添加的属性不具备响应式特点
        // 解决办法：使用 this.$set(目标对象，属性名称，初始值) 可以针对目标对象添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        // 缓存编辑的数据，为什么要缓存？因为编辑时候可以取消回滚到之前的状态，所以编辑时的数据是临时数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      // console.log(this.list)
      this.pageParams.total = total
    },
    // 点击分页事件
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    btnOK() {
      this.$refs.formData.validate(async isOk => {
        if (isOk) {
          await addRole(this.formData)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.showDialog = false
      this.formData.state = 0
      this.$refs.formData.resetFields()
    },
    // 编辑按钮
    btnEditRow(row) {
      row.isEdit = true
      console.log(row.state)
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      console.log(row)
    },
    // 行内编辑确定按钮
    async btnEditOk(row) {
      // 角色和描述都不能为空
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新成功')
        // 更新显示数据，退出编辑状态
        // row.isEdit = flase  这样写 eslint会报错 应该使用 Object.assign(target,source)
        Object.assign(row, {
          ...row.editRow, // 把缓存的更新后的数据回显到界面上
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述都不能为空')
      }
    },
    // 行内删除
    async confirmDelete(id) {
      // console.log(id)
      await delRole(id)
      this.$message.success('删除角色成功')
      // 如果删除的是最后一条 注意：这里需要考虑最后一页最后一条数据情况
      if (this.list.length === 1 && this.pageParams.page > 1) this.pageParams.page--
      this.getRoleList()
    },
    // 分配权限按钮功能
    async assignPermission(id) {
      // 获取所有权限列表 并转换为树结构
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.currentUserId = id
      // 根据角色获取角色拥有的权限
      const { permIds } = await getRoleDetail(id)
      console.log(permIds)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async assignOk() {
      console.log(this.permIds, this.currentUserId, typeof this.currentUserId, this.$refs.permTree.getCheckedKeys())
      await assignPerm({ id: this.currentUserId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate{
  padding: 10px;
}
</style>
